package com.plusjun.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.plusjun.common.constant.SecKillConstant;
import com.plusjun.common.to.mq.SeckillOrderTO;
import com.plusjun.common.utils.R;
import com.plusjun.common.vo.MemberRespVO;
import com.plusjun.seckill.feign.CuponFeignService;
import com.plusjun.seckill.feign.ProductFeignService;
import com.plusjun.seckill.interceptor.LoginUserInterceptor;
import com.plusjun.seckill.service.SeckillService;
import com.plusjun.seckill.to.SeckillSkuRedisTO;
import com.plusjun.seckill.vo.SeckillSessionWithSkus;
import com.plusjun.seckill.vo.SeckillSkuVO;
import com.plusjun.seckill.vo.SkuInfoVO;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    private CuponFeignService cuponFeignService;
    @Resource
    private ProductFeignService productFeignService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    @Override
    public void upSecKillSkuLatest3Days() {
        // 1、扫描需要参与秒杀的商品
        R r = cuponFeignService.getLastest3DaySession();
        if (r.getCode() == 0) {
            // 拿到上架商品
            List<SeckillSessionWithSkus> data = (List<SeckillSessionWithSkus>) r.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
            });
            // 将需要上架的商品先保存到redis中
            // 1、缓存活动信息
            saveSessionInfos(data);
            // 2、缓存活动相关的商品信息
            saveSessionSkuInfos(data);
        }

    }

    @Override
    public List<SeckillSkuRedisTO> getCurrentSeckillSkus() {

        // 当前时间属于哪个秒杀场次
        // 从1900.1.1 00:00:00到现在的时间戳
        long time = new Date().getTime();
        Set<String> keys = stringRedisTemplate.keys(SecKillConstant.SESSION_CACHE_PRIFIX + "*");
        for (String key : keys) {
            // key= seckill:session:1594569600000_1594486800000
            String newKey = key.replace(SecKillConstant.SESSION_CACHE_PRIFIX, "");
            String[] s = newKey.split("_");
            long start = Long.parseLong(s[0]);
            long end = Long.parseLong(s[1]);
            if (time >= start && time <= end) {
                // 2、获取这个秒杀场次的需要的所有信息
                List<String> range = stringRedisTemplate.opsForList().range(key, -1000, 1000);
                BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SecKillConstant.SKUKILL_CACHE_PRIFIX);
                List<String> list = hashOps.multiGet(range);
                if (!CollectionUtils.isEmpty(list)) {
                    List<SeckillSkuRedisTO> collect = list.stream().map(item -> {
                        SeckillSkuRedisTO toFromRedis = JSON.parseObject((String) item, SeckillSkuRedisTO.class);
                        return toFromRedis;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTO skuSeckillInfo(Long skuId) {
        // 找到所有需要参加秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SecKillConstant.SKUKILL_CACHE_PRIFIX);
        Set<String> keys = hashOps.keys();
        if (!CollectionUtils.isEmpty(keys)) {
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String s = hashOps.get(key);
                    SeckillSkuRedisTO redisTO = JSON.parseObject(s, SeckillSkuRedisTO.class);
                    // 随机码的处理
                    assert redisTO != null;
                    long now = new Date().getTime();
                    if (!(now >= redisTO.getStartTime() && now <= redisTO.getEndTime())) {
                        redisTO.setRandomCode(null);
                    }
                    return redisTO;
                }
            }
        }

        return null;
    }

    /**
     * TODO 上架秒杀的时候，每一个数据都有过期使劲啊
     * TODO 秒杀后续流程，简化了收获地址等信息
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String secKill(String killId, String key, Integer num) {
        MemberRespVO memberRespVO = LoginUserInterceptor.loginUser.get();
        // 获取当前的商品详情信息
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SecKillConstant.SKUKILL_CACHE_PRIFIX);
        String s = hashOps.get(killId);
        if (StringUtils.isEmpty(s)) {
            return null;
        } else {
            SeckillSkuRedisTO redisTO = JSON.parseObject(s, SeckillSkuRedisTO.class);
            Long startTime = redisTO.getStartTime();
            Long endTime = redisTO.getEndTime();
            long now = System.currentTimeMillis();
            long ttl = endTime - now;
            // 校验时间的合法性
            if (now >= startTime && now <= endTime) {
                // 校验随机码和商品id是否匹配
                String randomCode = redisTO.getRandomCode();
                String skuId = redisTO.getPromotionSessionId() + "_" + redisTO.getSkuId();
                if (Objects.equals(key, randomCode) && Objects.equals(skuId, killId)) {
                    // 验证购物数量是否合理
                    if (num <= redisTO.getSeckillCount()) {
                        // 验证这个人是否买过.幂等性处理：秒杀成功就去redis占位：userId_Session_skuId
                        String redisKey = SecKillConstant.MEMBER_HAS_PURCHASED + memberRespVO.getId() + "_" + skuId;
                        // 如果返回true，说明占位成功，这个人从来没买过   自动过期
                        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (Objects.equals(flag,true)) {
                            // 这个人没买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SecKillConstant.SKU_STOCK_SEMAPHORE + randomCode);
                            // 尝试去获取到信号量
                            boolean b = semaphore.tryAcquire(num);
                            if (b) {

                                // 秒杀成功，快速下单，发送MQ消息
                                String orderSn = IdWorker.getTimeId();
                                SeckillOrderTO seckillOrderTO = new SeckillOrderTO();
                                seckillOrderTO.setMemberId(memberRespVO.getId());
                                seckillOrderTO.setNum(num);
                                seckillOrderTO.setOrderSn(orderSn);
                                seckillOrderTO.setPromotionSessionId(redisTO.getPromotionSessionId());
                                seckillOrderTO.setSkuId(redisTO.getSkuId());
                                seckillOrderTO.setSeckillPrice(redisTO.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTO);

                                return orderSn;
                            }
                        }
                    }
                }
            }
        }
        //
        return null;
    }

    private void saveSessionInfos(List<SeckillSessionWithSkus> data) {
        data.stream().forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SecKillConstant.SESSION_CACHE_PRIFIX + startTime + "_" + endTime;
            boolean hasKey = stringRedisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> stringList = session.getRelationEntities().stream()
                        .map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                stringRedisTemplate.opsForList().leftPushAll(SecKillConstant.SESSION_CACHE_PRIFIX + startTime + "_" + endTime, stringList);
            }
        });
    }

    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> data) {
        // sku基本信息
        List<List<Long>> collect = data.stream().map(item -> {
            return item.getRelationEntities().stream().map(SeckillSkuVO::getSkuId).distinct().collect(Collectors.toList());
        }).distinct().collect(Collectors.toList());
        List<Long> skuIds = collect.stream().flatMap(item -> item.stream().map(i -> i)).distinct().collect(Collectors.toList());
        R r = productFeignService.getSkuInfos(skuIds);
        if (r.getCode() == 0) {
            List<SkuInfoVO> skuInfoVOS = (List<SkuInfoVO>) r.getData(new TypeReference<List<SkuInfoVO>>() {
            });
            data.forEach(item -> {
                BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(SecKillConstant.SKUKILL_CACHE_PRIFIX);
                item.getRelationEntities().forEach(seckillSkuVO -> {
                    // 1、设置随机码 id=1?xxxxx   没开始之前都抢不到
                    String token = UUID.randomUUID().toString().replace("-", "");
                    if (!ops.hasKey(seckillSkuVO.getPromotionSessionId().toString() + "_" + seckillSkuVO.getSkuId().toString())) {
                        // 缓存商品
                        SeckillSkuRedisTO redisTO = new SeckillSkuRedisTO();
                        // 1、sku基本信息
                        SkuInfoVO skuInfoVO = skuInfoVOS.stream().filter(i -> i.getSkuId().equals(seckillSkuVO.getSkuId())).findFirst().get();
                        redisTO.setSkuInfo(skuInfoVO);
                        // 2、sku秒杀信息
                        BeanUtils.copyProperties(seckillSkuVO, redisTO);
                        // 3、 设置上当前商品的秒杀信息
                        redisTO.setStartTime(item.getStartTime().getTime());
                        redisTO.setStartTime(item.getEndTime().getTime());
                        redisTO.setRandomCode(token);
                        ops.put(seckillSkuVO.getPromotionSessionId().toString() + "_" + seckillSkuVO.getSkuId().toString(), JSON.toJSONString(redisTO));

                        // 4、引入商品库存作为分布式信号量
                        RSemaphore semaphore = redissonClient.getSemaphore(SecKillConstant.SKU_STOCK_SEMAPHORE + token);
                        // 商品的数量作为信号量
                        semaphore.trySetPermits(seckillSkuVO.getSeckillCount());
                    }
                });
            });
        }
    }
}
